package com.me.customerdemo.controller;

import com.github.pagehelper.PageInfo;
import com.me.customerdemo.pojo.SalesPlan;
import com.me.customerdemo.service.SalesPlanService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SalesPlanController {
    
    // 初始化一个在当前类中使用的日志输出器
    private static Logger logger = LoggerFactory.getLogger(SalesPlanController.class);

    //@Autowired注解所标注的成员变量，其取值是Spring框架创建对象的
    @Autowired
    SalesPlanService salesplanService;


    @GetMapping("/Sales/SalesPlan_add")
    public ModelAndView salesplanAddview(){
        final ModelAndView mav = new ModelAndView("Sales/SalesPlan_add");
        return mav;
    }

    @GetMapping("/Sales/SalesPlan_list")
    public ModelAndView salesplanListView(
            @RequestParam(name="pageNum", required = true,defaultValue = "1") int pageNum,
            @RequestParam(name="pageSize", required = true,defaultValue = "5") int pageSize,
            @RequestParam(name="keyword" ,required = false) String keyword
    ) {

        final ModelAndView mav = new ModelAndView("Sales/SalesPlan_list");
        // 分页查询数据

        PageInfo<SalesPlan> page=salesplanService.findByKeyword(pageNum,pageSize,keyword);
        mav.addObject("page",page);
        mav.addObject("keyword",keyword);

        return mav;
    }

    @GetMapping("/Sales/SalesPlan_modify")
    public ModelAndView salesplanModifyView(
        @RequestParam(name = "id",required = true) int id
//            @RequestParam(name = "pageSize",required = false,defaultValue = "5") int pageSize,
//            @RequestParam(name = "pageNum",required = false,defaultValue = "1") int pageNum
    ){
            ModelAndView mav = new ModelAndView("Sales/SalesPlan_modify");
            // 查询要编辑的客户信息 并将它装入到环境
            SalesPlan salesplan = salesplanService.findById(id);
            mav.addObject("salesplan",salesplan);
            return mav;
    }

    @PostMapping("/Sales/SalesPlan_add")
    //@Validated注解标注的命令对象，表示该对象中的属性必须按照已定义的规则进行验证。
    //BindingResult参数中封装了有关验证的信息，重点是包含了哪些字段出错，以有相应的错误信息
    public ModelAndView salesplanAdd(@Validated SalesPlan salesplan, BindingResult bindingResult){
        ModelAndView mav = new ModelAndView("redirect:/Sales/SalesPlan_add");
        //验证SalesPlan实例中的每一个属性字段是否符合规则
        //如果符合规则，则保存数据，返回正常的视图
        //如果不符合规则，则返回错误信息到添加视图

        //1.编写验证代码
        //2.给视图环境添加错误信息及错误的字段
        //3.返回添加页面，同时还要在页面上显示用户刚填写的内容
        Map<String,String> errors = new HashMap<>();
        if(bindingResult.hasErrors()){
            //取出错误对象
            final List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for(FieldError error : fieldErrors){
                //从错误对象中取出相应的名称作为键，对应的错误信息作为值，放入到映射集合中。
                errors.put(error.getField(),error.getDefaultMessage());

            }
            mav.addObject("errors",errors);
            mav.addObject("salesplan",salesplan);
            mav.setViewName("Sales/SalesPlan_add");
        }else{
            boolean result = salesplanService.apply(salesplan);
            if (result){
                logger.info("管理员***，成功添加一个新客户 - " + salesplan);
            }else {
                logger.error("管理员***，新增客户信息失败 - " + salesplan);
            }
        }

        //调用服务层方法来保存数据
//        salesplanService.apply(salesplan);
        return mav;
    }

    @PostMapping("/Sales/SalesPlan_modify")
    public ModelAndView salesplanModify(
            SalesPlan salesplan,
            @RequestParam(name = "pageSize",required = false,defaultValue = "5") int pageSize,
            @RequestParam(name = "pageNum",required = false,defaultValue = "1") int pageNum,
            @RequestParam(name = "keyword",required = false) String keyword

    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/Sales/SalesPlan_list?pageSize=" + pageSize + "&pageNum=" + pageNum + "&keyword=" + (keyword == null? "" : URLEncoder.encode(keyword,"utf-8"));
        ModelAndView mav = new ModelAndView(redirectUrl);
        // 调用服务层 保存客户信息
        boolean result = salesplanService.modify(salesplan);
        return mav;
    }

    @GetMapping("/Sales/SalesPlan_remove")
    public ModelAndView salesplanRemove(
            @RequestParam(name = "id",required = true) int id,
            @RequestParam(name = "pageSize",required = false,defaultValue = "5") int pageSize,
            @RequestParam(name = "pageNum",required = false,defaultValue = "1") int pageNum,
            @RequestParam(name = "keyword",required = false) String keyword
    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/Sales/SalesPlan_list?pageSize=" + pageSize +
                "&pageNum=" +pageNum +
                "&keyword=" + (keyword == null? "": URLEncoder.encode(keyword,"utf-8"));
        ModelAndView mav=new ModelAndView(redirectUrl);

        boolean result = salesplanService.removeById(id);
        if (result){
            logger.info("管理员***，成功删除一个新客户 - " + id);
        }else {
            logger.error("管理员***，删除客户信息失败 - " + id);
        }
        return mav;
    }
}
